%%%====================================================================
%%% File    : pipe_result.erl
%%% Author  :  <vjache>
%%% Description: This is a simpliest pipe implementation. It may be 
%%%				 considered as a simple reference implementation of 
%%%				 a pipe callback module, and could be used for debug 
%%%				 purposes.
%%%
%%% Created : 24.03.2009
%%%====================================================================

-module(pipe_result).

%%
%% Include files
%%
-include("../include/pipe.hrl").
-include("../include/util.hrl").
%%
%% Exported Functions
%%
-export([
		 new/2,
		 open/1,
		 push/2,
		 flush/1,
		 close/1,
		 fold/4,
		 list/2,
		 test/1]).

%%====================================================================
%% API Functions
%%====================================================================

new(ResultId,ToPid) ->
	pipe:pipe_from_module(?MODULE, {ResultId,ToPid}, _NextPipe=terminal).

open({{ResultId,ToPid},terminal=_NextPipe}) -> %%PipeState
    {ResultId,ToPid}.
push({ResultId,ToPid},Item) ->
    ToPid!{ResultId,Item},
	{ResultId,ToPid}.
flush(S) ->
	S.
close(_S) ->
	ok.

fold(MonitorPid,ResultId,FoldFun,Acc0) when is_function(FoldFun, 2) ->
	MonitorRef=erlang:monitor(process, MonitorPid),
	fold_loop(MonitorRef,ResultId,FoldFun,Acc0).
fold_loop(MonitorRef,ResultId,FoldFun,Acc0) when is_function(FoldFun, 2) ->
	receive
		{ResultId,Item} when Item/=?EOF ->
			fold_loop(MonitorRef,ResultId,FoldFun,FoldFun(Item,Acc0));
		{ResultId,?EOF} ->
			fold_loop(MonitorRef,ResultId,FoldFun,Acc0);
		{'DOWN', MonitorRef, _Type, _Object, _Info} ->
			Acc0
	end.

list(MonitorPid,ResultId) ->
	fold(MonitorPid,ResultId,
		 fun(Item,Acc)->
									 [Item|Acc]
		 end,[]).

%%====================================================================
%% Test Functions
%%====================================================================

test(L) ->
	S=pipe:open(new(make_ref(),self())),
	{IterState,PipeState}=pipe:push_each(S, iter:from_list(L)),
	iter:close(IterState),
	pipe:close(PipeState).


%%====================================================================
%% Local Functions
%%====================================================================

